package com.rt.sms.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/17 0017.
 */
public class RTLogger {

   // private Logger logger = Logger.getLogger(RTLogger.class);

    /** log文件存放目录 */
    private static String logDir;

    /** 每个日志文件最大容量 */
    private static int logFileMaxMB = 1;

    private static Map<String,RTLogger> map=new HashMap<>();

    private static TYPE logLevel;

    private static SimpleDateFormat df1 = new SimpleDateFormat("yyyy");
    private static SimpleDateFormat df2 = new SimpleDateFormat("MMdd");
    private static SimpleDateFormat df3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS>>>");

    static {
        logLevel= TYPE.DEBUG;
        File file = new File(System.getProperty("user.dir"));
        String parentPath = file.getParent();
        logDir = parentPath+File.separator+"logs"+File.separator;
    }

    private String fileName;

    private int  maxSize=logFileMaxMB*1024*1024;



    public RTLogger(String fileName){
        this.fileName=fileName;
    }


    public static RTLogger getLogger(String fileName){
        if(fileName==null || fileName.length()==0){
            fileName="RTLog";
        }
        RTLogger rtLogger=map.get(fileName);
        if(rtLogger!=null){
            return rtLogger;
        }
        synchronized (RTLogger.class){
            rtLogger=new RTLogger(fileName);
            map.put(fileName,rtLogger);
        }
        return rtLogger;
    }

    public void debug(String str){
        debug(str,"","");
    }

    public void debug(String str,String userId,String cmdId){
        this.log(str,userId,cmdId, TYPE.DEBUG);
    }

    public void info(String str,String userId,String cmdId){
        this.log(str,userId,cmdId, TYPE.INFO);
    }

    public void warn(String str,String userId,String cmdId){
        this.log(str,userId,cmdId, TYPE.WARN);
    }

    public void error(String str,String userId,String cmdId){
        this.log(str,userId,cmdId, TYPE.ERROR);
    }

    public void error(Exception e,String userId,String cmdId){
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        String str = sw.toString();
        this.error(e.getMessage(),userId, cmdId);
        this.error(str,userId,cmdId);
    }

    public synchronized  void log(String str,String userId,String cmdId,TYPE type){
        if(type.compareTo(logLevel)<0){
            return;
        }
        try{
            Date date = new Date();
            String filePath=logDir+df1.format(date)+File.separator+df2.format(date);
            // 创建日志目录
            File path = new File(filePath);
            if(!path.exists()) {
                path.mkdirs();
            }
            File file=new File(filePath+File.separator+fileName+".log");
            PrintWriter pw =new PrintWriter(new FileWriter(file,true));
//            pw.print("PID=");
//            pw.print(SysUtils.getPID());
            print(pw, type);
            print(pw,">>>ThreadIdSize=");
            print(pw,Thread.getAllStackTraces().size());
            print(pw,">>>ThreadId=");
            print(pw,Thread.currentThread().getId());
            print(pw,">>>Time=");
           print(pw,df3.format(new Date()));
            if(userId!=null && userId.length()>0){
                print(pw,"UserId=");
                print(pw,userId);
                print(pw,">>>");
            }
            if(cmdId!=null && cmdId.length()>0){
                print(pw,"CmdId=");
                print(pw,cmdId);
                print(pw,">>>");
            }
            println(pw,str);
            pw.flush();
            pw.close();
            int iLogFileNo=1;
            if(file.length()>maxSize){
                while (true){
                    File backName=new File(filePath+File.separator+fileName+iLogFileNo+".log");
                    if (backName.exists()) {
                        iLogFileNo++;
                        continue;
                    }
                    file.renameTo(backName);
                    file.delete();
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void print(PrintWriter pw,Object str ){
        System.out.print(str);
        pw.print(str);

    }

    private void println(PrintWriter pw ,Object str){
        System.out.println(str);
        pw.println(str);
    }

    public enum  TYPE {
        DEBUG,INFO,WARN,ERROR
    }

    public static void main(String[] args){
        RTLogger.getLogger("").debug("ddddddd","191","4000");
    }

}
